<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\VerifyCode;
use app\common\model\User as UserModel;
use fast\Random;
use think\Db;
use think\Validate;
use think\Exception;
use think\Log;

/**
 * APP端登录注册接口
 */
class AppAuth extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 登录注册一体化接口
     * 根据手机号是否存在自动判断是登录还是注册
     * 
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     * @ApiParams (name="invite_code", type="string", required=false, description="邀请码，仅在新用户注册时使用")
     * @ApiParams (name="type", type="string", required=false, description="操作类型，可不传")
     */
    public function loginOrRegister()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $type = $this->request->post('type', 'login'); // 默认为登录
        
        // 只有在注册时才获取邀请码
        $invite_code = '';
        if ($type == 'register') {
            $invite_code = $this->request->post('invite_code', '');
        }

        // 验证参数
        if (!$mobile || !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('请输入正确的手机号');
        }
        if (!$code) {
            $this->error('请输入验证码');
        }

        // 验证验证码
        $verifyCodeModel = new VerifyCode();
        $verifyResult = $verifyCodeModel->verifyCode($mobile, $code, $type);
        if (!$verifyResult['code']) {
            $this->error($verifyResult['msg']);
        }

        // 查询用户是否存在
        $user = UserModel::getByMobile($mobile);

        // 用户存在，执行登录
        if ($user) {
            if ($user->status != 'normal') {
                $this->error('账号已被锁定');
            }
            
            // 直接登录
            $ret = $this->auth->direct($user->id);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success('登录成功', $data);
            } else {
                $this->error($this->auth->getError());
            }
        } 
        // 用户不存在，根据类型决定是否注册
        else {
            // 如果用户不存在，自动进行注册
            // 不再根据type区分，统一处理为注册流程
            
            // 注册用户
            $username = $mobile; // 用手机号作为用户名
            $password = Random::alnum(8); // 生成随机密码
            $email = ''; // 邮箱为空
            
            // 注册用户，只在注册时使用邀请码
            $ret = $this->auth->register($username, $password, $email, $mobile, $invite_code, []);
            
            if ($ret) {
                // 注册成功后自动登录
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success('登录成功', $data);
            } else {
                $this->error($this->auth->getError());
            }
        }
    }

    /**
     * 发送验证码
     * 
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="type", type="string", required=false, description="验证码类型，可不传，默认为login")
     */
    public function sendCode()
    {
        $mobile = $this->request->post('mobile');
        $type = $this->request->post('type', 'login'); // 默认为登录验证码

        // 验证手机号
        if (!$mobile || !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('请输入正确的手机号');
        }

        // 发送验证码
        $verifyCodeModel = new VerifyCode();
        $result = $verifyCodeModel->sendCode($mobile, $type);

        if ($result['code']) {
            $this->success($result['msg'], $result['data']);
        } else {
            $this->error($result['msg']);
        }
    }

    /**
     * 退出登录
     * 
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error('非法请求');
        }
        $this->auth->logout();
        $this->success('退出成功');
    }
}